package com.iwunu.gateway.service.impl;


import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.annotation.Resource;

import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Sort;
import org.springframework.data.mongodb.core.MongoTemplate;
import org.springframework.data.mongodb.core.query.Criteria;
import org.springframework.data.mongodb.core.query.Query;
import org.springframework.stereotype.Component;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.iwunu.gateway.entity.FLockLog;
import com.iwunu.gateway.entity.ImageMongo;
import com.iwunu.gateway.service.FaceLockService;
import com.iwunu.gateway.service.FacesLogMongodbService;
import com.iwunu.gateway.vo.FacesLockLogVo;
import com.iwunu.gateway.vo.LogVo;
import com.iwunu.iot.common.constant.ClientDataEnum;
import com.iwunu.iot.common.constant.ClientOpenTypeEnum;
import com.iwunu.iot.common.util.DateUtil;

@Component
public class FacesLogMongodbServiceImpl implements FacesLogMongodbService {
	
	@Resource
	private MongoTemplate mongoTemplate;
	@Autowired
	private FaceLockService faceLockService;
	public Map<String, Object>  getMyLog(Map<String, Object> fl, LogVo log) {
		Map<String, Object> resultMap = new HashMap<>();
		
		//当前页码 默认给了0
	    int pageSize = log.getPageSize()!=0?log.getPageSize():10;
	    //页面展示数据条数 默认给了 10
	    int currentPage = log.getCurrentPage()!=0?log.getCurrentPage():1;
	    //筛选条件
	    String userId = fl.get("userId").toString();
	    String clientId = fl.get("lockClientId").toString();
	    String lockId = fl.get("lockId").toString();
	    Query query = new Query().addCriteria(Criteria.where("userId").is(userId).and("clientId").is(lockId));
	    //动态拼接查询条件
	    if(StringUtils.isNotBlank(log.getStartTime())&&StringUtils.isNotBlank(log.getEndTime())){
	        query.addCriteria(Criteria.where("startTime").gte(log.getStartTime()).and("endTime").lte(log.getEndTime()));
	    }
	    if(log.getType()!=null){
	        query.addCriteria(Criteria.where("type").is(log.getType()));
	    }
	    if(log.isSucc()||log.isSucc()==false){
	        query.addCriteria(Criteria.where("isSucc").is(log.isSucc()));
	    } 
	    // 设置起始数 	// 设置查询条数
	    query.skip((currentPage - 1) * pageSize).limit(pageSize);
	    long totalCount = mongoTemplate.count(query,FLockLog.class);
		// 数据总页数
		int totalPage = (int) (totalCount % pageSize == 0 ? totalCount / pageSize : totalCount / pageSize + 1);
 
		// 设置记录总数和总页数
		resultMap.put("totalCount", totalCount);
		resultMap.put("totalPage", totalPage);
 
		// 按创建时间倒序
		query.with(new Sort(Sort.Direction.DESC, "createTime"));
		// 查询当前页数据集合
	    List<FacesLockLogVo> flcockLogs= new ArrayList<FacesLockLogVo>();
	    List<FLockLog> fLockLogList = mongoTemplate.find(query, FLockLog.class);
	    for(FLockLog flog:fLockLogList){
	    	FacesLockLogVo flogVo = new FacesLockLogVo();
	    		
	    	ImageMongo image = this.getSendImageDataByUser(clientId, flog.getPitNum());
	    		if(flog.getType()==ClientOpenTypeEnum.FACES.getType()&&image!=null) {
	    			flogVo.setNickName(image.getRemark());
	    			flogVo.setAvatar(image.getImageUrl());
	    		}else {
	    			flogVo.setNickName(fl.get("nickName").toString());
	    			flogVo.setAvatar(fl.get("avatar").toString());
	    		}
	    		flogVo.setClientId(clientId);
	    		flogVo.setCreateTime(flog.getCreateTime());
	    		flogVo.setSucc(flog.isSucc());
	    		flogVo.setType(Integer.valueOf(flog.getType()));
	    		flcockLogs.add(flogVo);
	    }
	    resultMap.put("content", flcockLogs);
		return resultMap;
	}
	
	public Map<String, Object>  getOtherLog(Integer lockId,String userId, String clientId,LogVo log,Integer role) {
		Map<String, Object> resultMap = new HashMap<>();
		 Query query = new Query();
		List<FacesLockLogVo> flcockLogVos= new ArrayList<FacesLockLogVo>();
		//当前页码 默认给了0
	    int pageSize = log.getPageSize()!=0?log.getPageSize():10;
	    //页面展示数据条数 默认给了 10
	    int currentPage = log.getCurrentPage()!=null?log.getCurrentPage():1;
	    //筛选条件
	    query.addCriteria(Criteria.where("userId").ne(userId).and("clientId").is(lockId).and("role").gt(role));
	    // 设置起始数 	// 设置查询条数
	    query.skip((currentPage - 1) * pageSize).limit(pageSize);
	    long totalCount = mongoTemplate.count(query,FLockLog.class);
		// 数据总页数
		int totalPage = (int) (totalCount % pageSize == 0 ? totalCount / pageSize : totalCount / pageSize + 1);
		// 设置记录总数和总页数
		resultMap.put("totalCount", totalCount);
		resultMap.put("totalPage", totalPage);
	    //动态拼接查询条件
	    if(StringUtils.isNotBlank(log.getStartTime())&&StringUtils.isNotBlank(log.getEndTime())){
	        query.addCriteria(Criteria.where("startTime").gte(log.getStartTime()).and("endTime").lte(log.getEndTime()));
	    }
	    if(log.getType()!=null){
	        query.addCriteria(Criteria.where("type").is(log.getType()));
	    }
	    if(log.isSucc()||log.isSucc()==false){
	        query.addCriteria(Criteria.where("isSucc").is(log.isSucc()));
	    } 
		// 按创建时间倒序
		query.with(new Sort(Sort.Direction.DESC, "createDate"));
	    //获取总条数
	    List<Map<String, Object>> members = faceLockService.selectRoleMembers(lockId, role);
	    List<FLockLog> fLockLogList = mongoTemplate.find(query, FLockLog.class);
	    for(FLockLog flog:fLockLogList){
	    	FacesLockLogVo flogVo = new FacesLockLogVo();
	    	for(Map<String, Object> cmd:members) {
	  
	    		if(flog.getType()==2||flog.getType()==3||flog.getType()==4||flog.getType()==5) {
		    		flogVo.setAvatar("https://iwunu.oss-cn-shenzhen.aliyuncs.com/lock/images/default.png");
		    		flogVo.setNickName(this.getTypeName(Integer.valueOf(flog.getType())));
	    		}else if(flog.getUserId().equals(cmd.get("userId"))) {
	    			flogVo.setAvatar(cmd.get("avatar").toString());
	    			flogVo.setNickName(cmd.get("nickName").toString());
	    		}else if(flog.getType()==ClientOpenTypeEnum.FACES.getType()) {
	    			ImageMongo image = this.getSendImageDataByUser( clientId, flog.getPitNum());
	    			flogVo.setNickName(image.getRemark());
	    			flogVo.setAvatar(image.getImageUrl());
	    		}else {
	    			continue;
	    		}
	    		flogVo.setClientId(clientId);
	    		flogVo.setCreateTime(flog.getCreateTime());
	    		flogVo.setSucc(flog.isSucc());
	    		flogVo.setType(Integer.valueOf(flog.getType()));
	    		flcockLogVos.add(flogVo);
	    	}
	    }
	    resultMap.put("currentPage", currentPage);
	    resultMap.put("pageSize", pageSize);
	    resultMap.put("content", flcockLogVos);
		return resultMap;
	}
	
	public Map<String, Object>  getAllLog(Integer lockId, String clientId,LogVo log) {
		Map<String, Object> resultMap = new HashMap<>();
		 Query query = new Query();
		List<FacesLockLogVo> flcockLogVos= new ArrayList<FacesLockLogVo>();
		//当前页码 默认给了0
	    int pageSize = log.getPageSize()!=0?log.getPageSize():10;
	    //页面展示数据条数 默认给了 10
	    int currentPage = log.getCurrentPage()!=null?log.getCurrentPage():1;
	    //筛选条件
	    query.addCriteria(Criteria.where("clientId").is(lockId.toString()));
	    // 设置起始数 	// 设置查询条数
	    query.skip((currentPage - 1) * pageSize).limit(pageSize);
	    long totalCount = mongoTemplate.count(query,FLockLog.class);
		// 数据总页数
		int totalPage = (int) (totalCount % pageSize == 0 ? totalCount / pageSize : totalCount / pageSize + 1);
		// 设置记录总数和总页数
		resultMap.put("totalCount", totalCount);
		resultMap.put("totalPage", totalPage);
	    //动态拼接查询条件
	    if(StringUtils.isNotBlank(log.getStartTime())&&StringUtils.isNotBlank(log.getEndTime())){
	        query.addCriteria(Criteria.where("startTime").gte(log.getStartTime()).and("endTime").lte(log.getEndTime()));
	    }
	    if(log.getType()!=null&&log.getType()!=0){
	        query.addCriteria(Criteria.where("type").is(log.getType()));
	    }
		// 按创建时间倒序
		query.with(new Sort(Sort.Direction.DESC, "createTime"));
	    //获取总条数
	    List<Map<String, Object>> members = faceLockService.selectMembers(lockId);
	    List<FLockLog> fLockLogList = mongoTemplate.find(query, FLockLog.class);
	    for(FLockLog flog:fLockLogList){
	    	FacesLockLogVo flogVo = new FacesLockLogVo();
	    	for(Map<String, Object> cmd:members) {
	    		if(flog.getType()==2||flog.getType()==3||flog.getType()==4||flog.getType()==5) {
		    		flogVo.setAvatar("https://iwunu.oss-cn-shenzhen.aliyuncs.com/lock/images/default.png");
		    		flogVo.setNickName(this.getTypeName(Integer.valueOf(flog.getType())));
	    		}else if(flog.getType()==ClientOpenTypeEnum.FACES.getType()) {
	    			ImageMongo image = (ImageMongo)this.getSendImageDataByUser( clientId, flog.getPitNum());
	    			if(image==null) {continue;}
	    			flogVo.setNickName(image.getRemark());
	    			flogVo.setAvatar(image.getImageUrl());
	    		}else if(flog.getUserId().equals(cmd.get("userId").toString())) {
	    			flogVo.setAvatar(cmd.get("avatar")==null? "https://iwunu.oss-cn-shenzhen.aliyuncs.com/lock/images/default.png":cmd.get("avatar").toString());
	    			flogVo.setNickName(cmd.get("nickName")==null?this.getTypeName(Integer.valueOf(flog.getType())):cmd.get("nickName").toString());
	    		}else {
	    			continue;
	    		}
	    		flogVo.setClientId(clientId);
	    		flogVo.setCreateTime(flog.getCreateTime());
	    		flogVo.setSucc(flog.isSucc());
	    		flogVo.setType(Integer.valueOf(flog.getType()));
	    		flcockLogVos.add(flogVo);
	    	}
	    }
	    resultMap.put("currentPage", currentPage);
	    resultMap.put("pageSize", pageSize);
	    resultMap.put("content", flcockLogVos);
		return resultMap;
	}
	public  String getTypeName(Integer type) {
		String result ="";
		switch (type) {
		
		case 2:
			result= "超级密码";
			break;
		case 3:
			result= "机械开锁";
			break;
		case 4:
			result= "离线密码";
			break;
		case 5:
			result= "离线卡";
			break;
		default:
			break;
		}
		return result;
	}
	/**
	 * *获取锁的个人人脸数据
	 * @param userId
	 * @param clientId
	 * @param type
	 * @return
	 */
	public ImageMongo  getSendImageDataByUser(String clientId,Integer pitNum) {
		Query query = new Query(Criteria.where("clientId").is(clientId).and("isSucc").is(true).and("pitNum").is(pitNum));
		return mongoTemplate.findOne(query, ImageMongo.class);
	}
}
